package com.xingshi.springbootinit.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingshi.springbootinit.common.ErrorCode;
import com.xingshi.springbootinit.exception.BusinessException;
import com.xingshi.springbootinit.exception.ThrowUtils;
import com.xingshi.springbootinit.mapper.ChartMapper;
import com.xingshi.springbootinit.model.entity.Chart;
import com.xingshi.springbootinit.service.ChartService;
import com.xingshi.springbootinit.websocket.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 图表操作实现
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
    implements ChartService{

    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 更新图表状态异常统一处理
     * @param chartId
     * @param execMessage
     */
    public void handleChartUpdateError(Long chartId, String execMessage) {
        Chart updateToFailed = new Chart();
        updateToFailed.setId(chartId);
        updateToFailed.setStatus("failed");
        updateToFailed.setExecMessage(execMessage);
        boolean update = updateById(updateToFailed);

        //通知客户端图表生成失败
        String notice = "糟糕！有图表生成失败了，再重新试试吧！";
        webSocketServer.sendToAllClient(notice);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新图表状态失败，请联系系统管理员！");
        }
    }

    /**
     * 校验文件
     * @param multipartFile
     */
    public void validFile(MultipartFile multipartFile) {
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        final long ONE_MB = 1024*1024L;
        ThrowUtils.throwIf(size > ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1M");
        final List<String> validFileSuffixList = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix),ErrorCode.PARAMS_ERROR,"文件后缀非法");
    }

    /**
     * 构造用户输入
     * @param chart
     * @return
     */
    public String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");

        return userInput.toString();
    }


    /**
     * 解析字符串
     * @param genChart
     * @return
     */
    public boolean isValidJson(String genChart){
        try {
            // 尝试解析genChart字符串
            JSONUtil.parseObj(genChart);
            return true; // 如果解析成功，返回true
        } catch (JSONException e) {
            // 捕获解析错误，返回false
            return false;
        }
    }
}




